package com.example.mybatis.my.shop.controller;
import java.util.Date;

import com.example.mybatis.my.shop.entity.TbUser;
import com.example.mybatis.my.shop.service.TbUserService;
import com.example.mybatis.my.shop.service.impl.TbUserServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(value = "/saveUser")
public class UserSaveController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        TbUserService tbUserService = new TbUserServiceImpl();
        String id = req.getParameter("id");
        String email = req.getParameter("email");
        String passWord = req.getParameter("passWord");
        String userName = req.getParameter("userName");
        String phone = req.getParameter("phone");

        TbUser tbUser = new TbUser();
        tbUser.setId(Long.parseLong(id));
        tbUser.setUserName(userName);
        tbUser.setPassWord(DigestUtils.md5Hex(passWord));
        tbUser.setPhone(phone);
        tbUser.setEmail(email);
        tbUser.setCreated(new Date());
        tbUser.setUpdated(new Date());

        //当id不为null的时候，为修改用户信息
        if(id != null){
            int result = tbUserService.updateUser(tbUser);
            if(result>0){
                req.setAttribute("message","修改成功！！！");
                req.getRequestDispatcher("/userList").forward(req,resp);
            }else {
                req.setAttribute("message","修改失败！！！");
                req.getRequestDispatcher("/user_form.jsp").forward(req,resp);
            }
        }
        //否则为添加用户信息
        else{
            int i = tbUserService.insertUser(tbUser);
            if(i>0){
                req.setAttribute("message","添加成功！！！");
                req.getRequestDispatcher("/userList").forward(req,resp);
            }else {
                req.setAttribute("message","添加失败！！！");
                req.getRequestDispatcher("/user_form.jsp").forward(req,resp);
            }
        }

    }
}
